﻿(function () {
    MyOrdersClass = {};
    var isScrollLoad = false;
    var loadType = 0;//请求数据方式，0，下拉分页加载，1搜索
    var winH = $(window).height(); //页面可视区域高度
    var lastRequestCount = 0;
    var _spid = ToolManager.Common.UrlParms("spid");
    var _said = ToolManager.Common.UrlParms("said");
    var _canback = ToolManager.Common.UrlParms("canback");
    var paydata = {};
    var _orderNo = "";
    var criteria = {
        OffSet: 1,
        Size: 10,
        OrderStatus: ToolManager.Common.UrlParms("orderStatus")
    };
    MyOrdersClass.Instance = {
        Init: function () {
            lastRequestCount = $(".weui-content").attr("LoadRequstCount");
            $(window).scroll(MyOrdersClass.Instance.ScrollHandler);
            $(document).on('click', '.weui-navbar__item', this.Jump);
            $(document).on('click', '.goPayClass', this.GoToPay);
            $(document).on('click', '.goServiceClass', this.GoService);
        },
        GoService: function () {
            var orderId = $(this).attr("OrderId");
            layer.confirm('确认要发起售后吗？', {
                btn: ['确认', '取消'] //按钮
            }, function () {
                var index = layer.load(1);
                $.get("/Order/ServiceOrder?orderid=" + orderId + "&spid="+_spid+"&r=" + new Date().getTime(), function (data) {
                    layer.close(index);
                    if (data.IsSuccess) {
                        layer.alert("申请售后成功，请添加客服微信沟通", function () {
                            window.location.reload();
                        });

                    } else {
                        layer.msg(data.Message);
                    }
                })
            }, function () {
                layer.msg("已取消");
            });
        },
        GoToPay: function () {
            var orderno = $(this).attr("OrderNo");
            var index = layer.load(1);
            $.get("/Order/GetPayData?orderno=" + orderno + "&spid="+_spid+"&r=" + new Date().getTime(), function (data) {
                layer.close(index);
                if (data.IsSuccess) {
                    //获取证书并构建
                    paydata["appId"] = data.Data.PayParamater.AppId;
                    paydata["timeStamp"] = data.Data.PayParamater.TimeStamp;
                    paydata["nonceStr"] = data.Data.PayParamater.NonceStr;
                    paydata["package"] = data.Data.PayParamater.Package;
                    paydata["signType"] = data.Data.PayParamater.SignType;
                    paydata["paySign"] = data.Data.PayParamater.PaySign;
                    _orderNo = data.Data.PayParamater.Orderno;
                    MyOrdersClass.Instance.ToPay();
                } else {
                    layer.msg(data.Message);
                }
            })
        },
        ToPay: function () {
            if (typeof WeixinJSBridge == "undefined") {
                if (document.addEventListener) {
                    document.addEventListener('WeixinJSBridgeReady', MyOrdersClass.Instance.onBridgeReady, false);
                } else if (document.attachEvent) {
                    document.attachEvent('WeixinJSBridgeReady', MyOrdersClass.Instance.onBridgeReady);
                    document.attachEvent('onWeixinJSBridgeReady', MyOrdersClass.Instance.onBridgeReady);
                }
            } else {
                MyOrdersClass.Instance.onBridgeReady();
            }
        },
        onBridgeReady: function () {
            WeixinJSBridge.invoke(
            'getBrandWCPayRequest', paydata,
            function (res) {
                if (res.err_msg.indexOf('ok') > -1) {
                    MyOrdersClass.Instance.GoResult();
                } else if (res.err_msg.indexOf('cancel') > -1) {
                    layer.msg("用户取消了支付。");
                } else {
                    layer.msg("支付出现错误，支付失败。");
                    try {
                        $.get("/Error/Write?error=" + JSON.stringify(res) + "&r=" + new Date().getTime(), function (data) {
                            if (data.IsSuccess) {

                            } else {
                                layer.alert(data.Message);
                            }
                        })
                    } catch (e) { }

                    //alert(res.err_msg);//使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                }
            }
            )
        },
        GoResult: function () {
            var index = layer.load(1);
            $.get("/Order/GetPayResult?orderno=" + _orderNo + "&spid="+_spid+"&r=" + new Date().getTime(), function (data) {
                layer.close(index);
                if (data.IsSuccess) {
                    var result = data.Data;
                    if (result.code == "SUCCESS") {
                        switch (result.state) {
                            case "SUCCESS":
                                //window.location.href = "./orderinfo.aspx?spid=" + $("#hid_spid").val() + "&orderno=" + orderno;
                                //跳转支付成功页面
                                window.location.href = "/Order/MyOrders?orderStatus=999&spid=" + _spid + "&said=" + _said + "&canback=0";
                                break;
                            case "USERPAYING":
                                layer.msg("支付处理中");
                                setTimeout(MyOrdersClass.Instance.GoResult, 4000);
                                break;
                            case "REFUND":
                            case "NOTPAY":
                            case "CLOSED":
                            case "PAYERROR":
                            case "REVOKED":
                                layer.msg("支付处理中");
                                break;
                        }

                    }
                    else {
                        layer.alert(result.msg, { icon: 0 });

                    }
                }
                else {
                    layer.alert(data.Message, { icon: 0 });

                }
            })



        },
        Jump: function () {
            var os = $(this).attr("Os");
            if (_canback == "null" || _canback==null)
                window.location.href = "/Order/MyOrders?orderStatus=" + os + "&spid=" + _spid + "&said=" + _said
            else
                window.location.href = "/Order/MyOrders?orderStatus=" + os + "&spid=" + _spid + "&said=" + _said + "&canback=" + _canback;
        },

        ScrollHandler: function () {
            if (isScrollLoad || lastRequestCount < criteria.Size) {
                return false;
            }

            var pageH = $(document.body).height();
            var scrollT = $(window).scrollTop(); //滚动条top   
            var aa = (pageH - winH - scrollT) / winH;
            if (aa < 0.3) {//0.02是个参数  
                isScrollLoad = true;
                loadType = 0;
                MyOrdersClass.Instance.Request();
            }
        },
        Request: function () {
            $(".weui-loadmore").show();

            RequestManager.Ajax.Post("/Order/SearchOrders?spid=" + _spid, criteria, true, function (data) {
                $(".weui-loadmore").hide();
                if (data.IsSuccess) {
                    $(".weui-loadmore").hide();

                    lastRequestCount = data.Data.length;
                    if (data.Data.length > 0) {
                        criteria.OffSet = criteria.OffSet + 1;

                        var htmlArr = [];
                        for (var i = 0; i < data.Data.length; i++) {
                            htmlArr.push('<div class="weui-panel weui-panel_access">')
                            htmlArr.push('<div class="weui-panel__hd">');
                            htmlArr.push('<span>单号:' + data.Data[i].OrderNo + '</span><span class="ord-status-txt-ts fr">' + ToolManager.Common.ConvertOrderStatus(data.Data[i].OrderStatus) + '</span>');
                            htmlArr.push('</div>');
                            htmlArr.push('<div class="weui-media-box__bd  pd-10">');
                            htmlArr.push('<div class="weui-media-box_appmsg ord-pro-list">');
                            htmlArr.push('<div class="weui-media-box__hd">');
                            htmlArr.push('<a href="/Product/Detail?spid=' + _spid + '&said=' + _said + '&id=' + data.Data[i].ProductId + '"><img class="weui-media-box__thumb" src="' + data.Data[i].ImagePath + '" alt=""></a>');
                            htmlArr.push('</div>');
                            htmlArr.push('<div class="weui-media-box__bd">');
                            htmlArr.push(' <h1 class="weui-media-box__desc"><a href="/Product/Detail?spid=' + _spid + '&said=' + _said + '&id=' + data.Data[i].ProductId + '" class="ord-pro-link">' + data.Data[i].ProductName + '</a></h1>');

                            htmlArr.push(' <p class="weui-media-box__desc">规格:<span>' + (data.Data[i].ProppetyCombineName == "" ? data.Data[i].ProductName : data.Data[i].ProppetyCombineName) + '</span></p>');
                            htmlArr.push(' <div class="clear mg-t-10">');
                            htmlArr.push('<div class="wy-pro-pri fl">¥<em class="num font-15">' + data.Data[i].SalePrice + '</em></div>');
                            htmlArr.push(' <div class="pro-amount fr"><span class="font-13">数量×<em class="name">' + data.Data[i].BuyNum + '</em></span></div>');
                            htmlArr.push('</div>');
                            htmlArr.push('</div>');
                            htmlArr.push('</div>');
                            htmlArr.push('</div>');
                            htmlArr.push('<div class="ord-statistics">');
                            htmlArr.push('<span>共<em class="num">' + data.Data[i].ProductNum + '</em>件商品，</span>')
                            htmlArr.push(' <span class="wy-pro-pri">总金额：¥<em class="num font-15">' + data.Data[i].RealityAmount + '</em></span>');
                            htmlArr.push('</div>');
                            htmlArr.push('<div class="weui-panel__ft">');
                            htmlArr.push('<div class="weui-cell weui-cell_access weui-cell_link oder-opt-btnbox">');
                            htmlArr.push('<a href="/Home/Index?spid=' + _spid + '&said=' + _said + '" class="ords-btn-dele">查看详情</a>');
                            switch (data.Data[i].OrderStatus) {
                                case 0:
                                    htmlArr.push('<a href="javascript:;" OrderNo="' + data.Data[i].OrderNo + '" class="ords-btn-dele goPayClass">去付款</a>');
                                    break;
                                case 1:
                                    htmlArr.push('<a href="javascript:;" OrderNo="' + data.Data[i].OrderNo + '" class="ords-btn-dele goServiceClass">申请售后</a>');
                                    break;
                            }
                            htmlArr.push('<a href="/Order/Detail?orderId=' + data.Data[i].OrderID + '&spid=' + _spid + '&said=' + _said + '" class="ords-btn-dele">查看详情</a>');
                            htmlArr.push('</div>');
                            htmlArr.push('</div>');
                            htmlArr.push('</div>');
                        }
                        if (loadType == 0)
                            $("#list_div").append(htmlArr.join(''));
                        else
                            $("#list_div").html(htmlArr.join(''));
                    } else {
                        //搜索
                        if (loadType == 1)
                            $("#list_div").html(' <div style="text-align:center">暂无订单</div>');
                    }
                    isScrollLoad = false;
                } else {
                    layer.alert(data.Message);
                }
            })

        },



    };

})();